import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/core/utils/user_manager.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/edu_get_user_by_id_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/auth/company_api_config_entity.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';
import 'package:get/get.dart';

/// 首页 我的
class HomeMyController extends GetxController {
  EduGetUserByIdEntity? entity;

  Future<void> getDetailsData({void Function()? callback, bool force = false}) async {
    if (!force && entity != null) return;
    final res = await HttpUtil().generateGetRequest<EduGetUserByIdEntity>(
      Interface.getEnterpriseUserById,
      queryParameters: {'userId': UserManager.getUserId()},
    ).execute();
    res.onSuccess((result) {
      final data = result.data;
      if (data != null) {
        entity = data;
        callback?.call();
        update();
        if (entity?.companyCode!= null) {
          getConfigByCode();
        }
      }
    });
  }

  // 根据企业唯一编码获取配置
  void getConfigByCode() async {
    final res = await HttpUtil().generateGetRequest<CompanyApiConfigEntity>(Interface.getConfigByCode, queryParameters: {
      'companyCode': entity?.companyCode,
    }).execute();
    res.onSuccess((result) {
      final data = result.data;
      if (data != null) {
        // 瓦片地址
        Interface.tilesetUrl = data.tileAddress.first;
        // 地形地址
        Interface.terrainUrl = data.terrainAddress.first;
      }
    });
  }

  Future<void> updateProfile() async {
    final res = await HttpUtil().generatePostRequest<String>(Interface.updateUser, data: entity?.toJson()).execute(isShowLoading: true);
    res.onSuccess((result) {
      Get.back();
      AppToast.showSuccess('更新成功!');
      update();
    });
  }

  @override
  void onInit() {
    super.onInit();
    // 未登录不执行操作
    if (!UserManager.isLoggedIn) {
      return;
    }
    onInitData();
  }

  Future<void> onInitData() async {
    await getDetailsData();
    // 如果用户信息不完善,跳转到个人信息页面完善
    if (entity != null && (entity!.signatureUrl.isEmpty || entity!.faceUrl.isEmpty)) {
      AppToast.showWarning('请完善用户信息!');
      Get.toNamed(AppRoutes.myProfile);
    }
  }
}
